package com.zenitera.bigdata.timer;

import com.zenitera.bigdata.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * 定时器
 * 基于事件时间的定时器
 * 注册:registerEventTimeTimer && 注销:deleteEventTimeTimer
 */
public class Flink02_Timer_EventTimeTimer_01 {
    public static void main(String[] args) throws Exception {

        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        env
                .socketTextStream("localhost", 6666)
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(
                            data[0],
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forMonotonousTimestamps()
                                .withTimestampAssigner((ws, ts) -> ws.getTs())
                )
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private long ts;

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        out.collect(ctx.getCurrentKey() + " 超出10了!");
                    }

                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        if (value.getVc() > 10) {
                            ts = value.getTs() + 4000;
                            System.out.println("注册定时器: " + value.getId() + " > " + ts);
                            ctx.timerService().registerEventTimeTimer(ts);
                        } else if (value.getVc() < 10) {
                            System.out.println("取消定时器: " + value.getId() + " > " + ts);
                            ctx.timerService().deleteEventTimeTimer(ts);
                        }

                    }
                })
                .print();


        env.execute();
    }
}

/*
D:\netcat-win32-1.12>nc64.exe -lp 6666
s1,1,12
s1,1,6
s2,1,3
s2,1,14
s3,1,15
s2,1,2
s3,1,2
-----------------
注册定时器: s1 > 4001
取消定时器: s1 > 4001
取消定时器: s2 > 4001
注册定时器: s2 > 4001
注册定时器: s3 > 4001
取消定时器: s2 > 4001
取消定时器: s3 > 4001
 */